package galaxies;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.jme3.asset.AssetManager;

import controller.AbstractController;
import controller.IController;
import eventManager.EventManager;

import galaxies.enums.EGalaxyType;
import gameAppLayer.GameSettings;
import universe.UniverseBuilder;
import utilities.HexLocationLoader;
import utilities.MVCMaker;
import view.EViewList;
import view.AbstractView;

public class GalaxyCustomBuilder {

	private static final Logger logger = Logger.getLogger(GalaxyCustomBuilder.class.getName());
	
	private HashMap<Integer, ArrayList<Integer>> galaxyTileLocations;
	private double scaleFactor;
	
	public ArrayList<IController> createGalaxy(
			GameSettings settings, 
			AssetManager assetManager, 
			String galRef, 
			ArrayList<ArrayList<Integer>> dims, 
			CustomGalaxyData data) {
		
		logger.log(Level.INFO, "CREATING GALAXY");
		int galSize = settings.getGalSizes(galRef);
		GalaxyModel model = new GalaxyModel(galSize, settings.getGalaxyType(galRef), settings.getGalaxyDensity(galRef));
		GalaxyViewBuilder viewBuild = new GalaxyViewBuilder();
		HashMap<EViewList, AbstractView> view = viewBuild.buildViews(assetManager);
		GalaxyController controller = new GalaxyController();
		
		MVCMaker.linkElements(model, view, controller);
		
		ArrayList<IController> controllers = new ArrayList<IController>();
		controllers.add(controller);
		logger.log(Level.INFO, "GALAXY CREATED");
		
		//Given dims and points from data, calculate scale factor for galaxy
		double dist;
		double maxDist = 0;		
		double x, y;
		double x2, y2;
		
		//Find furthest point of galaxy bounding box
		for (ArrayList<Integer> point: dims) {
			x = point.get(0);
			y = point.get(1);			
			
			dist = Math.sqrt(x*x + y*y);
			if (dist > maxDist) {
				maxDist = dist;				
			}			
		}		
		double dimDist = maxDist;
		
		//find furthest point from loaded data (galaxy shape)
		maxDist = 0;
		ArrayList<ArrayList<Double>> galaxyRawPoints = data.getPoints();		
		for (ArrayList<Double> point: galaxyRawPoints) {
			x2 = point.get(0);
			y2 = point.get(1);
			
			dist = Math.sqrt(x2*x2 + y2*y2);
			if (dist > maxDist) {
				maxDist = dist;				
			}			
		}
		double pointDist = maxDist;
		
		logger.log(Level.INFO, "Bounding box max. dist= " + dimDist);
		logger.log(Level.INFO, "Loaded points max. dist= " + pointDist);
		
		//scale multiplier to shift dimensions of galaxyRawPoints
		scaleFactor = 0.95*dimDist/pointDist;		
		
		//Load hex locations
		galaxyTileLocations = HexLocationLoader.loadLocations((int) dimDist);
		model.setLocations(galaxyTileLocations);		
		
		return controllers;
	}
	
	public double getScaleFactor() {
		return this.scaleFactor;
	}

	public HashMap<Integer, ArrayList<Integer>> getLocations() {
		return this.galaxyTileLocations;
	}
}
